package com.woniuxy.sales.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.woniuxy.sales.common.enumeration.OrderStatus;
import com.woniuxy.sales.config.AlipayConfig;
import com.woniuxy.sales.model.entity.Orders;
import com.woniuxy.sales.model.vo.CartItemVo;
import com.woniuxy.sales.model.vo.OrderVo;
import com.woniuxy.sales.model.vo.PayRequest;
import com.woniuxy.sales.service.OrdersService;
import com.woniuxy.sales.untils.JwtTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/orders")
@Api(tags = "订单管理")
@Slf4j
public class OrdersController {
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private JwtTemplate jwtTemplate;
    @Autowired
    private AlipayConfig alipayConfig;

    /**
     * 支付宝异步回调接口
     * http://内网穿透地址/orders/notify
     */
    @PostMapping("/notify")
    @ApiOperation("支付回调")
    public void alipayNotify(HttpServletRequest request) throws AlipayApiException {
        //获取所有请求参数，重新创建一个Map再封装一次数据
        Map<String,String> params=request.getParameterMap().entrySet().stream()
                .collect(Collectors.toMap(Map.Entry::getKey,e->e.getValue()[0]));
        // 验证签名
        log.info("支付宝回调参数：{}", params);
        String sign = params.get("sign");
        String contentV1 = AlipaySignature.getSignCheckContentV1(params);
        boolean rsa256CheckSignature = AlipaySignature.rsa256CheckContent(contentV1,
                sign, alipayConfig.getAlipayPublicKey(), "UTF-8");
        //表示支付成功
        if (rsa256CheckSignature && "TRADE_SUCCESS".equals(params.get("trade_status"))) {
            // 签名验证成功 并且 支付宝回调的状态是成功状态 TRADE_SUCCESS
            log.info("在{}，买家{}进行订单{}的付款，交易名称{}，付款金额{}", params.get("gmt_payment"), params.get("buyer_id"),
                    params.get("out_trade_no"), params.get("subject"), params.get("total_amount"));

            // 支付成功，修改数据库中该订单的状态，out_trade_no即订单ID
            String outTradeNo = params.get("out_trade_no");
            //更新订单状态为待发货

            ordersService.updateOrderStatus(Long.valueOf(outTradeNo), OrderStatus.PAID.getCode());

            log.info("订单{}支付成功，状态修改为待发货", outTradeNo);
        } else {
            log.error("支付宝支付失败");
        }
    }


    /**
     * 支付接口
     * @return 返回一个包含表单数据的HTML网页
     */
    @PostMapping("/pay")
    @ApiOperation("支付接口")
    public ResponseEntity<String> pay(@RequestBody PayRequest request){
        //调用业务层支付
        String form = ordersService.pay(Long.valueOf(request.getOrderId()));
        return ResponseEntity.ok(form);
    }

    /**
     * 查询订单
     */
    @GetMapping("/loadOrdersByStatus")
    @ApiOperation("查询指定状态的订单")
//从 HTTP 请求的头部中获取 Authorization 字段的值。required = false意味着这个头部字段是可选的。也就是说，用户可能会发送一个包含令牌的请求，也可能不会。
    public ResponseEntity<List<OrderVo>> loadOrdersByStatus(@RequestHeader(name = "Authorization", required = false) String token,
                                                            Integer status) {
        //从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        //调用业务层查询订单
        List<OrderVo> orderVos = ordersService.queryOrder(userId, status);
        return ResponseEntity.ok(orderVos);
    }

    @PostMapping("/create/{addressId}")
    @ApiOperation("创建订单")
    public ResponseEntity<String> create(@RequestHeader(name = "Authorization", required = false) String token,
                                         @PathVariable Integer addressId) {
        //从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        //调用业务层创建订单
        String orderId = ordersService.createOrder(userId, addressId);
        return ResponseEntity.ok("订单提交成功，订单号：" + orderId);
    }
    @PostMapping("/createBySelection/{addressId}/{totalPrice}")
    @ApiOperation("根据选中项创建订单")
    public ResponseEntity<String> createBySelection(@RequestHeader(name = "Authorization", required = false) String token,
                                                     @RequestBody List<CartItemVo> cartItemVos,
                                                    @PathVariable Integer addressId,
                                                    @PathVariable Double totalPrice) {
        //从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        //调用业务层创建订单
        String orderId = ordersService.createBySelection(userId,cartItemVos, addressId,totalPrice);
        return ResponseEntity.ok("订单提交成功，订单号：" + orderId);
    }


    @ApiOperation("取消订单")
    @PostMapping("/cancel/{orderId}")
    public ResponseEntity<String> cancelOrder(
            @RequestHeader(name = "Authorization", required = false) String token,
            @PathVariable Long orderId) {
        // 从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));

        try {
            // 调用业务层取消订单
            ordersService.cancelOrder(orderId, userId);
            return ResponseEntity.ok("订单已成功取消，订单号：" + orderId);
        } catch (RuntimeException e) {
            // 捕获可能发生的异常（例如订单不存在或不可取消的情况）
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        }
    }

    @PostMapping("/createByBuy/{addressId}")
    @ApiOperation("立即购买时创建订单")
    public ResponseEntity<String> createByBuy(@RequestHeader(name = "Authorization", required = false) String token,
                                                    @RequestBody CartItemVo cartItemVo,
                                                    @PathVariable Integer addressId) {
        //从token中获取userId
        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));
        //调用业务层创建订单
        String orderId = ordersService.createByBuy(userId,cartItemVo, addressId);
        return ResponseEntity.ok("订单提交成功，订单号：" + orderId);
    }

    @PostMapping("/updateShipmentStatus")
    public ResponseEntity<String> updateShipmentStatus(@RequestParam Long orderId, @RequestParam Integer shipmentStatus) {
        Orders order = ordersService.getById(orderId);
        if (order != null) {
            order.setShipmentStatus(shipmentStatus);
            ordersService.updateById(order);
            return ResponseEntity.ok("发货状态更新成功");
        }
        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("订单未找到");
    }

}




